import { login, logout, getInfo } from '@/api/acl/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()


// 厨师
const mutations = {
  RESET_STATE: (state) => {
    // 从源对象 把所有可枚举的 和自有属性 复制到目标对象
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}


// 服务员
const actions = {
  // 登录
  login({ commit }, userInfo) {
    // 解构出来 用户名  和密码
    const { username, password } = userInfo
    // 返回一个promise
    return new Promise((resolve, reject) => {
      // 登录的请求函数
      login({ username: username.trim(), password: password }).then(response => {
        // 请求成功的话  拿到里面的data
        const { data } = response
      
        // 提交厨师 存下来token  在vuex里面
        commit('SET_TOKEN', data.token)
        // 调用方法 本地 持久存一份token
        setToken(data.token)
        // 返回成功的结果
        resolve()
      }).catch(error => {
        reject(error)
        
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户  退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 删除 token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // 第一步先清除token
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

